package com.laoli.service.impl;
import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laoli.entity.*;
import com.laoli.mapper.*;
import com.laoli.remote.OrderRemoteService;
import com.laoli.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: edu-lagou
 * @Author: GuoAn.Sun
 * @CreateTime: 2020-10-16 16:16
 * @Description:
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private LessonMapper lessonMapper;
    @Autowired
    private SectionMapper sectionMapper;
    @Autowired
    private MediaMapper mediaMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private OrderRemoteService remoteService;


    @Override
    public List<CourseDTO> getAllCourse() {
        //查询全部课程
        //将redis内存中的序列化的集合名称用String重新命名（增加可读性）
        RedisSerializer rs = new StringRedisSerializer();
        redisTemplate.setKeySerializer(rs);
        //1.去redis查询数据集合
        System.out.println("---------------------》》》查询redis");
        List<CourseDTO> courseDTOS = (List<CourseDTO>)redisTemplate.opsForValue().get("allCourses");

        //课程集合dto
        if(courseDTOS == null){
            synchronized (this){
                //排队，让第一一个人进，走遍流程(后面的人航会走缓存了)
                courseDTOS = (List<CourseDTO>)redisTemplate.opsForValue().get("allCourses");
                if(courseDTOS == null){
                    System.out.println("===查询mysql===");
                    List<Course> courses = getInitCourse(null);
                    courseDTOS=new ArrayList<>();
                    for (Course course : courses) {
                        CourseDTO courseDTO=new CourseDTO();
                        BeanUtils.copyProperties(course,courseDTO);
                        courseDTOS.add(courseDTO);
                        //设置老师
                        setTeacher(courseDTO);
                        //设置前两节课
                        setTop2Lesson(courseDTO);
                    }

                    //3.将数据集合放入redis，以便下次查询使用
                    redisTemplate.opsForValue().set("allCourses",courseDTOS,10, TimeUnit.SECONDS);
                }
            }
        }
        return courseDTOS;
    }
    //查询已登录用户购买的全部课程信息
    @Override
    public List<CourseDTO> getCoursesByUserId(Integer userid) {
        //根据用户id获取已近购买的课程集合
        List<Object> ids = remoteService.getOkOrderCouesrIds(userid);
        System.out.println("获取到的ids="+ids);
        return this.getMyCourse(ids);
    }

    //初始化基本的全部课程
    private List<Course> getInitCourse(List<Object> ids){
        QueryWrapper q=new QueryWrapper();
        q.eq("status",1);//已上架
        q.eq("is_del",Boolean.FALSE);//未删除
        if(ids!=null){
            q.in("id",ids);
        }
        q.orderByDesc("sort_num");//排序
        return this.courseMapper.selectList(q);
    }
    //初始化基本的老师查询
    private void setTeacher(CourseDTO course){
        QueryWrapper q=new QueryWrapper();
        q.eq("course_id",course.getId());//已上架
        q.eq("is_del",Boolean.FALSE);//未删除
        Teacher teacher = this.teacherMapper.selectOne(q);
        course.setTeacher(teacher);
    }

    //前两节课查询
    private void setTop2Lesson(CourseDTO courseDTO){
        QueryWrapper q=new QueryWrapper();
        q.eq("course_id",courseDTO.getId());//一个课程,一个老师
        q.eq("is_del",Boolean.FALSE);//未删除
        q.orderByDesc("section_id","order_num");//排序
        q.last("limit 0,"+2);//只要前两条数据
        List<CourseLesson> list = this.lessonMapper.selectList(q);
        courseDTO.setLesson2(list);
    }

   /*@Override
    public List<Course> getMyCoursesById(List<String> idList) {
        return courseMapper.getMyCoursesById(idList);
    }*/
    @Override
    public CourseDTO getCourseById(Integer courseid) {
        QueryWrapper<Course> q=new QueryWrapper();
        q.eq("id",courseid);
        CourseDTO courseDTO=new CourseDTO();
        Course course = this.courseMapper.selectOne(q);
        BeanUtils.copyProperties(course,courseDTO);
        //关联老师
        setTeacher(courseDTO);
        //关联章节
        List<SectionDTO> sectionDTOS = getCourseSection(courseDTO);
        courseDTO.setCourseSections(sectionDTOS);
        return courseDTO;
    }
    //关联章节
    private List<SectionDTO> getCourseSection(CourseDTO courseDTO) {
        QueryWrapper q=new QueryWrapper();
        q.eq("course_id",courseDTO.getId());//一个课程,N章
        q.eq("is_del",Boolean.FALSE);//未删除
        q.eq("status",2);//已发布
        q.orderByDesc("order_num");//排序
        //基本的章节查询
        List<CourseSection> list = this.sectionMapper.selectList(q);
        //关联的章节集合
        List<SectionDTO> sectionDTOS=new ArrayList<>();
        for (CourseSection courseSection : list) {
            SectionDTO sectionDTO=new SectionDTO();
            BeanUtils.copyProperties(courseSection,sectionDTO);
            //关联每节课的信息
            q.clear();//清除条件
            q.eq("section_id",sectionDTO.getId());//已发布
            q.eq("is_del",Boolean.FALSE);//未删除
            q.orderByDesc("order_num");//排序
            //某章节的全部小结(基本信息)
            List<CourseLesson> lessons = this.lessonMapper.selectList(q);
            //某章节的全部视频(关联信息)
            List<LessonDTO> lessonDTOS=new ArrayList<>();
            for (CourseLesson lesson : lessons) {
                LessonDTO lessonDTO=new LessonDTO();
                BeanUtils.copyProperties(lesson,lessonDTO);

                //设置每节课对应的视频
                setMedia(lessonDTO);
                lessonDTOS.add(lessonDTO);
            }
            //章节关联所有小节
            sectionDTO.setCourseLessons(lessonDTOS);

            //某个章节放入到章节集合
            sectionDTOS.add(sectionDTO);
        }
        return sectionDTOS;
    }

    //每节课的视频
    private void setMedia(LessonDTO lessonDTO){
        QueryWrapper q=new QueryWrapper();
        q.eq("lesson_id",lessonDTO.getId());//已上架
        q.eq("is_del",Boolean.FALSE);//未删除
        CourseMedia courseMedia= this.mediaMapper.selectOne(q);
       lessonDTO.setCourseMedia(courseMedia);
    }



    //查询已近购买的课程
    private List<CourseDTO> getMyCourse(List<Object> ids) {
        //查询全部课程
        //将redis内存中的序列化的集合名称用String重新命名（增加可读性）
        RedisSerializer rs = new StringRedisSerializer();
        redisTemplate.setKeySerializer(rs);
        //1.去redis查询数据集合
        System.out.println("---------------------》》》查询redis");
        List<CourseDTO> courseDTOS = (List<CourseDTO>)redisTemplate.opsForValue().get("myCourses");

        //课程集合dto
        if(courseDTOS == null){
            synchronized (this){
                //排队，让第一一个人进，走遍流程(后面的人航会走缓存了)
                courseDTOS = (List<CourseDTO>)redisTemplate.opsForValue().get("myCourses");
                if(courseDTOS == null){
                    System.out.println("===查询mysql===");
                    List<Course> courses = getInitCourse(ids);
                    courseDTOS=new ArrayList<>();
                    for (Course course : courses) {
                        CourseDTO courseDTO=new CourseDTO();
                        BeanUtils.copyProperties(course,courseDTO);
                        courseDTOS.add(courseDTO);
                        //设置老师
                        setTeacher(courseDTO);
                        //设置前两节课
                        setTop2Lesson(courseDTO);
                    }

                    //3.将数据集合放入redis，以便下次查询使用
                    redisTemplate.opsForValue().set("myCourses",courseDTOS,10, TimeUnit.SECONDS);
                }
            }
        }
        return courseDTOS;
    }
}
